<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/10/22
 * Time: 15:58
 * 代言人
 */
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\AgentOrder;
use app\common\model\AgentShop;
use app\common\service\UserService;
use think\Db;
use app\admin\model\User as UserModel;

class Promotion extends Api {
	
	/**
	 * 统计
	 */
	public function statistics() {
		$userId = $this->auth->id;
		$level = $this->auth->level;
		if($level != UserModel::LEVEL_PROMOTION) {
			$this->error('权限不足');
		}
		
		$agentInfo = Db::name('Promotion')
			->where(['user_id' => $userId])
			->field('sale_number, order_number, mobile, sale_amount, status')
			->find();
		if($agentInfo && $agentInfo['status'] == \app\common\model\Promotion::STATUS_D) {
			$this->error('当前身份已被禁用');
		}
		
		//访客数
//		$visible = Db::name('Visitor')->where(['share_user_id' => $userId])->count();
		
		
		//粉丝
		$fans = UserService::getFansNumById($userId);
		
		//佣金
		$commission = Db::name('commission')->where(['user_id' => $userId])->sum('amount');
		
		//余额
		$balance = $this->auth->money;
		
		//代言人数量
		$promotion = Db::name('promotion')->where(['recommend_user_id' => $userId, 'status' => \app\common\model\Promotion::STATUS_Y])->count();
		
		//提货点数量
		$warehouse = Db::name('agentShop')
			->where([
				'recommend_user_id' => $userId,
				'role' => UserModel::LEVEL_WAREHOUSE,
				'status' => AgentShop::STATUS_Y
				])
			->count();
		
		
		//奖励数量
		$reward = Db::name('order')
			->where(['user_id' => $userId, 'order_type' => \app\common\model\Order::TYPE_REWARD])
			->sum('number');
		
		
		$this->success('查询成功', [
//			'visible' => $visible,
			'info' => ($agentInfo && $agentInfo['mobile']) ? 1 : 0,
			'order_number' => $agentInfo ? $agentInfo['order_number'] : 0,
			'sale_number' => $agentInfo ? $agentInfo['sale_number'] : 0,
			'order_amount' => $agentInfo ? $agentInfo['sale_amount']:0,
			'fans' => $fans,
			'commission' => round($commission, 2),
			'balance' => $balance,
			'promotion' => $promotion,
			'warehouse' => $warehouse,
			'reward_number' => $reward ? : 0
		]);
	}
	
	/**
	 * 创建订单
	 */
	public function createOrder() {
		$userId = $this->auth->id;
		if($this->auth->level != UserModel::LEVEL_USER) {
			$this->error('你已经有推广权限');
		}
		
		if($this->area == UserModel::AREA_OTHER) {
			$setting = Db::name('setting')->find();
		} else {
			$setting = Db::name('ruleSz')->find();
		}
		
		if(!$setting || $setting['level_agent_amount'] <= 0) {
			$this->error('敬请开放加盟');
		}
		
		$rid = $this->request->post('rid');
		!$rid && $this->error('请通过邀请开通代言人');
		$parent = UserModel::get($rid);
		if(!$parent || $parent['level'] == UserModel::LEVEL_USER) {
			$this->error('代理才可邀请代言人');
		}
		$model = new AgentOrder();
		$row = $model->where(['user_id' => $userId])->find();
		if(!$row) {
			
			$res = $model->isUpdate(false)
				->save([
					'recommend_user_id' => $rid,
					'user_id' => $userId,
					'level' => UserModel::LEVEL_PROMOTION,
					'amount' => $setting['level_agent_amount'],
				]);
			if(!$res) {
				$this->error('创建订单出错');
			}
			
			$id = $model->getLastInsID();
		} else {
			$res = $model->save(['amount' => $setting['level_agent_amount'], 'recommend_user_id' => $rid], ['id' => $row['id']]);
			if($res === false) {
				$this->error('创建订单出错');
			}
			$id = $row['id'];
		}
		
		$notifyUrl = $this->request->domain() . url('api/notify/promotion', '', false);
		$config = config('weixin');
		$obj = new \app\common\library\Weixin($config['smallapp']['app_id']);
		
		$user = UserModel::get($userId);
		$data = $obj->unifiedOrder($id, $setting['level_agent_amount'],$notifyUrl, $user['smallapp_openid']);
		$this->success($data['msg'], $data['data'], $data['code']);
		
	}
	
	/**
	 * 填写资料
	 */
	public function edit(){
		$data = $this->request->post();
		$check = new \app\common\validate\Promotion();
		if(!$check->check($data)) {
			$this->error($check->getError());
		}
		
		$userId = $this->auth->id;
		$order = Db::name('agentOrder')
			->where(['user_id' => $userId, 'level' => UserModel::LEVEL_PROMOTION, 'status' => AgentOrder::STATUS_Y])
			->find();
		if(!$order) {
			$this->error('请先支付入驻金额');
		}
		
		$user = Db::name('user')->find($userId);
		$agentId = '';
		if($user['recommend_user_id']) {
			$agentShop= Db::name('agentShop')->where(['user_id' => $order['recommend_user_id']])->find();
			if($agentShop) {
				$agentId = $agentShop['id'];
			}
		}
		
		
		$model = new \app\common\model\Promotion();
		$row = $model->where(['user_id' => $userId])->find();
		$data['user_id'] = $userId;
		$data['agent_shop_id'] = $agentId;
		$data['recommend_user_id'] = $user['recommend_user_id'] ? : '';
		$data['status'] = 1;
		if($row) {
			unset($data['id']);
			$res = $model->allowField(true)->save($data, ['id' => $row['id']]);
		} else {
			$res = $model->allowField(true)->isUpdate(false)->save($data);
		}
		
		if($res !== false) {
			$this->success('保存成功', $model->getLastSql());
		}	 else {
			$this->error('保存出错，请稍候重试');
		}
	}
}
